package com.hnust.service.impl;

import java.util.*;

import com.hnust.dao.*;
import com.hnust.domain.*;
import com.hnust.domain.Class;
import com.hnust.domain.record.*;
import com.hnust.domain.record.QuestionRecordRecord;
import com.hnust.service.ExerciseService;
import com.hnust.util.IDUtil;
import com.hnust.util.JwtToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("exerciseService")
public class ExerciseServiceImpl implements ExerciseService {
    @Autowired
    private ClassAboutDao classAboutDao;
    @Autowired
    private PaperAboutDao paperAboutDao;
    @Autowired
    private QuestionDao questionDao;
    @Autowired
    private QuestionRecordDao questionRecordDao;
    @Autowired
    private StudentDao studentDao;
    @Autowired
    private ClassDao classDao;


    //实体类转中间类
    @Override
    public List<CollegeRecord> getCollege() {
        List<College> colleges = classAboutDao.getAllCollege();
        List<CollegeRecord> collegeRecords = new ArrayList<>();
            for (College college : colleges) {
                CollegeRecord collegeRecord = new CollegeRecord();
                collegeRecord.setColId(college.getColId());
                collegeRecord.setName(college.getName());
                collegeRecords.add(collegeRecord);
            }
            return collegeRecords;
        }

    @Override
    public List<CourseRecord> getCourse(String collegeId) {
        List<Course> courses = paperAboutDao.getAllCourse(collegeId);
        List<CourseRecord> courseRecords = new ArrayList<>();
            for (Course course : courses) {
                CourseRecord courseRecord = new CourseRecord();
                courseRecord.setCouId(course.getCouId());
                courseRecord.setName(course.getName());
                courseRecord.setCouNumber(course.getCouNumber());
                courseRecords.add(courseRecord);
            }
            return courseRecords;
    }

    @Override
    public List<ChapterRecord> getChapter(String courseId,Integer level) {
        List<Chapter> chapters = paperAboutDao.getAllChapter(courseId);
        List<ChapterRecord> chapterRecords = new ArrayList<>();
        List<QuestionType> questionTypes = paperAboutDao.getAllQuestionType();
            for (Chapter chapter : chapters) {
                int count = 0;
                ChapterRecord chapterRecord = new ChapterRecord();
                chapterRecord.setChaId(chapter.getChaId());
                chapterRecord.setName(chapter.getName());
                chapterRecord.setCouId(chapter.getCouId());
                chapterRecord.setChapter(chapter.getChapter());
                chapterRecord.setFirst(chapter.getFirst());
                chapterRecord.setSecond(chapter.getSecond());
                chapterRecord.setThird(chapter.getThird());
                List<QueTypeCountRecord> queTypeCountRecordList = new ArrayList<>();
                for (QuestionType questionType : questionTypes) {
                    QueTypeCountRecord queTypeCountRecord = new QueTypeCountRecord();
                    queTypeCountRecord.setQueTypId(questionType.getQueTypId());
                    Integer queTypeCounts = 0;
                    if(level == null){
                        queTypeCounts = questionDao.getQueTypeCount(chapterRecord.getChaId(), queTypeCountRecord.getQueTypId());
                    }else {
                        queTypeCounts = questionDao.getQueTypeCountByLevel(chapterRecord.getChaId(), queTypeCountRecord.getQueTypId(), level);
                    }
                    if (queTypeCounts != 0) {
                        count++;
                    }
                    queTypeCountRecord.setCount(queTypeCounts);
                    queTypeCountRecordList.add(queTypeCountRecord);
                }
                if (count != 0) {
                    chapterRecord.setQueTypeCount(queTypeCountRecordList);
                } else {
                    chapterRecord.setQueTypeCount(null);
                }

                chapterRecords.add(chapterRecord);
            }
            return chapterRecords;
    }

    @Override
    public List<QuestionTypeRecord> getQuestionType() {
        List<QuestionType> questionTypes = paperAboutDao.getAllQuestionType();
        List<QuestionTypeRecord> questionTypeRecords = new ArrayList<>();
            for (QuestionType questionType : questionTypes) {
                QuestionTypeRecord questionTypeRecord = new QuestionTypeRecord();
                questionTypeRecord.setQueTypId(questionType.getQueTypId());
                questionTypeRecord.setName(questionType.getName());
                questionTypeRecords.add(questionTypeRecord);
            }
            return questionTypeRecords;
    }

    @Override
    public List<NewQuestionRecordRecord> getQuestion(List<ExerciseQuestInfoRecord> typeInfoList, List<String> chapterIdList, Integer level) {
        List<NewQuestionRecordRecord> questionRecordRecords = new ArrayList<>();
        for (ExerciseQuestInfoRecord typeInfo : typeInfoList) {
            for (int i = 0; i < chapterIdList.size(); i++) {
                    if(typeInfo.getCount()==0)
                        continue;
                    List<Question> questions = null;
                    if(level == null){
                        questions = questionDao.getQuestionByInfoNoLevel(chapterIdList.get(i), typeInfo.getQueTypeID(), typeInfo.getCount());
                    }else {
                        questions = questionDao.getQuestionByInfo(chapterIdList.get(i), typeInfo.getQueTypeID(), level, typeInfo.getCount());
                    }
                    typeInfo.setCount(typeInfo.getCount()-questions.size());
//                    System.out.println(chapterIdList.get(i)+" 类型："+typeInfo.getQueTypeID()+" 题目："+questions.size());
                    for (Question question : questions) {
                        NewQuestionRecordRecord questionRecordRecord = new NewQuestionRecordRecord();
                        questionRecordRecord.setQueId(question.getQueId());
                        questionRecordRecord.setContent(question.getContent());
                        questionRecordRecord.setAnalysis((question.getAnalysis()));
                        questionRecordRecord.setPoint(question.getPoint());
                        questionRecordRecord.setLevel(question.getLevel());
                        questionRecordRecord.setType(typeInfo.getQueTypeID());
                        List<AlternativeAnswer> alternativeAnswers = questionDao.getAlternativeAnswer(question.getQueId());
                        List<AlternativeAnswerRecord> alternativeAnswerRecordList = new ArrayList<>();
                        for (AlternativeAnswer alternativeAnswer : alternativeAnswers) {
                            AlternativeAnswerRecord alternativeAnswerRecord = new AlternativeAnswerRecord();
                            alternativeAnswerRecord.setContent(alternativeAnswer.getContent());
                            if (alternativeAnswer.getRight() == 1) {
                                alternativeAnswerRecord.setRight(true);
                            } else {
                                alternativeAnswerRecord.setRight(false);
                            }
                            alternativeAnswerRecordList.add(alternativeAnswerRecord);
                            questionRecordRecord.setAnswer(alternativeAnswerRecordList);
                        }
                        questionRecordRecords.add(questionRecordRecord);
                    }
                }
            }
        return questionRecordRecords;
    }

    @Override
    public String addRecord(List<String> questionIdList, String createTime, String studentId, String queRecType, String token, Boolean right) {
        Integer rig = 0;
        Map<String, String> map = null;
        try {
            map = JwtToken.verifyToken(token);
        } catch (Exception e) {
            return "无效令牌";
        }
        String idInToken = map.get("id");
        String passwordInToken = map.get("password");
        if (!idInToken.equals(studentId)) {
            return "用户不匹配";
        }
        Student student = null;
        try {
            student = studentDao.queryStudentById(idInToken);
        } catch (Exception e) {
            return "用户不存在";
        }
        if (!student.getPassword().equals(passwordInToken)) {
            return "用户不匹配";
        }
        try {
            if(right == null){
                rig = 3;
            }else {
                if (right) {
                    rig = 1;
                } else {
                    rig = 2;
                }
            }
            for(String quedtionId : questionIdList) {
                String queRecId = IDUtil.getPrimaryKey();
                questionRecordDao.addRecord(queRecId, rig, createTime, createTime, createTime, studentId, quedtionId, queRecType);
            }

            return "添加记录成功";
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public Map<String, Object> getRanking(String collageId, String majorId, String classId, Integer type, String studentId, Integer offset, Integer limit) {
        String msg = "排名获取成功";
        List<Student> students = new ArrayList<>();
          if(collageId !=null){
            try{
                if(majorId==null){
                    List<Class> classes = classDao.queryClassByCollageId(collageId);
                    for(Class classItem : classes){
                        students.addAll(studentDao.queryStudentsByClassId(classItem.getClaId()));
                    }
                }else{
                    if(classId==null) {
                        List<Class> classes = classDao.queryClassByMajorId(majorId);
                        for (Class classItem : classes) {
                            students.addAll(studentDao.queryStudentsByClassId(classItem.getClaId()));
                        }
                    }else{
                            students = studentDao.queryStudentsByClassId(classId);
                        }
                }
            }catch (Exception e){
                msg = "获取学生列表失败";
                Map<String, Object> resMap = new HashMap<>();
            resMap.put("msg",msg);
            return resMap;
            }
        }else{
            try{
                students = studentDao.queryAllStudent();
            }catch (Exception e){
                msg = "获取学生列表失败";
                Map<String, Object> resMap = new HashMap<>();
            resMap.put("msg",msg);
            return resMap;
            }
        }
        RankInfoRecord me = null;
        List<RankInfoRecord> rankInfoRecords = new ArrayList<>();
        try {
            for (Student student : students) {
                RankInfoRecord rankInfoRecord = new RankInfoRecord();
                if(studentId.equals(student.getStuId())){
                    me = rankInfoRecord;
                }
                rankInfoRecord.setStuID(student.getStuId());
                rankInfoRecord.setAlias(student.getAlias());
                rankInfoRecord.setGrade(classDao.getGradeByClassId(student.getClsId()));
                if(rankInfoRecord.getGrade()==null){
                    rankInfoRecord.setGrade("无记录");
                }
                rankInfoRecord.setAmount(questionRecordDao.countQuestionRecord(student.getStuId()));
                if(rankInfoRecord.getAmount()==0) {
                    rankInfoRecord.setAccuracy((float)0);
                } else {
                    rankInfoRecord.setAccuracy(questionRecordDao.countRightQuestionRecord(student.getStuId()) / (float) rankInfoRecord.getAmount());
                }
                rankInfoRecords.add(rankInfoRecord);
            }
        }catch (Exception e){
            msg = "获取学生列表失败";
            Map<String, Object> resMap = new HashMap<>();
            resMap.put("msg",msg);
            return resMap;
        }
        if(type==2) {//刷题量
            Collections.sort(rankInfoRecords, new Comparator<RankInfoRecord>() {
                @Override
                public int compare(RankInfoRecord o1, RankInfoRecord o2) {
                    if(o1.getAmount() < o2.getAmount()) {
                        return 1;
                    } else {
                        return -1;
                    }
                }
            });
        }else{
            Collections.sort(rankInfoRecords, new Comparator<RankInfoRecord>() {
                @Override
                public int compare(RankInfoRecord o1, RankInfoRecord o2) {
                    if(o1.getAccuracy() < o2.getAccuracy()) {
                        return 1;
                    } else {
                        return -1;
                    }
                }
            });
        }
        int myRank = rankInfoRecords.indexOf(me)+1;
        Integer totalPage = (int)Math.ceil(rankInfoRecords.size()/(double)limit);
        if(offset<0){
            offset=0;
        }
        int target = offset+limit;
        if(target>rankInfoRecords.size()){
            target = rankInfoRecords.size();
        }
        List<RankInfoRecord> resultList = rankInfoRecords.subList(offset,target);
        Map<String, Object> result = new HashMap<>();
        if(myRank == -1) {
            myRank = 0;
        }
        result.put("myRank",myRank);
        result.put("totalPage",totalPage);
        result.put("allStudent",resultList);
        result.put("msg",msg);
        return result;
    }

    @Override
    public List<NewQuestionRecordRecord> getQuestionsByCourseIdAndPage(String courseId,int page, String chapterId) {
        List<NewQuestionRecordRecord> questionRecordRecords = new ArrayList<>();
        List<Question> questions = null;
        long offset = (page-1)*20;
        if(chapterId.isEmpty()){
            questions = questionDao.getQuestionsByCourseIdAndOffset(courseId,offset,null);
        }else{
            //对章节ID进行处理 使得questions放入所有下属章节的题目
            questions = questionDao.getQuestionsByCourseIdAndOffset(courseId,offset,chapterId);
        }

        for (Question question : questions) {
            NewQuestionRecordRecord questionRecordRecord = new NewQuestionRecordRecord();
            questionRecordRecord.setQueId(question.getQueId());
            questionRecordRecord.setContent(question.getContent());
            questionRecordRecord.setAnalysis((question.getAnalysis()));
            questionRecordRecord.setPoint(question.getPoint());
            questionRecordRecord.setLevel(question.getLevel());
            questionRecordRecord.setType(question.getQueTypId());
            List<AlternativeAnswer> alternativeAnswers = questionDao.getAlternativeAnswer(question.getQueId());
            List<AlternativeAnswerRecord> alternativeAnswerRecordList = new ArrayList<>();
            for (AlternativeAnswer alternativeAnswer : alternativeAnswers) {
                AlternativeAnswerRecord alternativeAnswerRecord = new AlternativeAnswerRecord();
                alternativeAnswerRecord.setContent(alternativeAnswer.getContent());
                if (alternativeAnswer.getRight() == 1) {
                    alternativeAnswerRecord.setRight(true);
                } else {
                    alternativeAnswerRecord.setRight(false);
                }
                alternativeAnswerRecordList.add(alternativeAnswerRecord);
                questionRecordRecord.setAnswer(alternativeAnswerRecordList);
            }
            questionRecordRecords.add(questionRecordRecord);
        }
        return questionRecordRecords;
    }

    @Override
    public List<ChapterTreeItemRecord> getChapterTree(String courseId) throws Exception{
        List<Chapter> chapterList = null;
        try {
            chapterList = paperAboutDao.getAllChapter(courseId);
        }catch (Exception e){
            throw new Exception("章节列表获取失败");
        }
        List<ChapterTreeItemRecord> treeL1Layer = new ArrayList<>();

        //排序开始
        //生成树
        for(int i=0; i<chapterList.size(); i++) {
            Chapter nowChapterItem = chapterList.get(i);
            String title = (nowChapterItem.getChapter()==0?"":nowChapterItem.getChapter().toString())
                    + (nowChapterItem.getFirst()==0?"":("."+nowChapterItem.getFirst().toString()))
                    + (nowChapterItem.getSecond()==0?"":("."+nowChapterItem.getSecond().toString()))
                    + (nowChapterItem.getThird()==0?"":("."+nowChapterItem.getThird().toString()))
                    + nowChapterItem.getName();
            ChapterTreeItemRecord chapterTreeItemRecord = new ChapterTreeItemRecord(
                    title,
                    nowChapterItem.getChaId(),
                    nowChapterItem.getFirst(),
                    nowChapterItem.getSecond(),
                    nowChapterItem.getThird(),
                    nowChapterItem.getChapter(),
                    new ArrayList<>(),
                    true);
            if(chapterTreeItemRecord.getFirst()==0){
                treeL1Layer.add(chapterTreeItemRecord);
            }else if(chapterTreeItemRecord.getSecond()==0){
                treeL1Layer.get(treeL1Layer.size()-1).setSelectable(false);
                treeL1Layer.get(treeL1Layer.size()-1).getChildren().add(chapterTreeItemRecord);
            }else if(chapterTreeItemRecord.getThird()==0){
                treeL1Layer.get(treeL1Layer.size()-1).getChildren().get(treeL1Layer.get(treeL1Layer.size()-1).getChildren().size()-1).setSelectable(false);
                treeL1Layer.get(treeL1Layer.size()-1).getChildren().get(treeL1Layer.get(treeL1Layer.size()-1).getChildren().size()-1).getChildren().add(chapterTreeItemRecord);
            }
        }
        //排序结束
        return treeL1Layer;
    }
}



